<script setup lang="ts">
import { computed, h, reactive, ref, watch } from 'vue'; // 导入 computed 和 watch

import {
  CloudDownloadOutlined,
  CloudUploadOutlined,
  LinkOutlined,
  RedoOutlined,
  SearchOutlined,
  HistoryOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue';
import * as XLSX from 'xlsx';
import { useRoute } from 'vue-router';
import {
  getBuildingTableSearch,
  getHeatSourceTable,
  getHeatStationTableSearch,
  getHeatUserInfo,
  getVillageTableSearch,
  getRoomBatchOperation_eleven,
  getAccountButtonAuth,
} from '#/api';

import FileUpload from './fileUpload.vue';
import HistoryTable from './historyTable.vue';
import UploadTemplate from './uploadTemplate.vue';
import DetailRY from './detailsRY.vue';
import DetailXQ from './detailsXQ.vue';
import DetailRZ from './detailsRZ.vue';
import DetailUser from './detailsUser.vue';
import BatchDelete from './batchDelete.vue';

import { message } from 'ant-design-vue';
// 定义 props
interface Props {
  selectedType: string;
  selectedNodeId: any[];
  selectedLevel: number;
}
const props = defineProps({
  selectedType: {
    type: String,
    default: '',
  },
  selectedNodeId: {
    type: Array,
    default: () => [],
  },
  selectedLevel: {
    type: Number,
    default: 0,
  },
});
const authInfo = ref<Record<string, any>>({});
const router = useRoute();
const getAuth = () => {
  const query = {
    pageId: router.meta.id,
    userId: localStorage.getItem('userId'),
  };
  getAccountButtonAuth(query).then((res: any) => {
    // console.log(res)
    authInfo.value = res.data.data;
  });
  // console.log(router);
};
getAuth();

const onModel = ref(false);
const historyModel = ref(false);
const open = ref(false);
const isDel = ref(false);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    getTableData();
  },
});
const showSearch = ref(false);
const searchText = ref('');
const isRefreshing = ref(false);
const tableData = ref<any[]>([]);

const handleSearch = () => {
  if (!searchText.value.trim()) {
    showSearch.value = false;
  }
  getTableData();
  // 这里添加搜索逻辑
  // TODO: 实现实际的搜索功能
};

const handleRefresh = () => {
  if (isRefreshing.value) return;

  isRefreshing.value = true;

  // TODO: 在此处添加实际的刷新逻辑

  setTimeout(() => {
    isRefreshing.value = false;
  }, 1000); // 旋转动画持续1秒
};

const columns = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    align: 'center',
  },
  {
    title: '热源站名称(财务)',
    dataIndex: 'heatSourceNameACC',
    align: 'center',
  },
  {
    title: '投产时间',
    dataIndex: 'createdTime',
    align: 'center',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    align: 'center',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    align: 'center',
  },
  {
    title: '热源的建设性质',
    dataIndex: 'heatSourceBelong',
    align: 'center',
  },
  {
    title: '供热模式',
    dataIndex: 'heatingMode',
    align: 'center',
  },
  {
    title: '是否完成',
    dataIndex: 'isCompleted',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    align: 'center',
  },
];
const columns_RZ = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'comNameLevel4',
    align: 'center',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    align: 'center',
  },
  {
    title: '换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '换热站名称(财务)',
    dataIndex: 'heatExchangeStationNameACC',
    align: 'center',
  },
  {
    title: '站级',
    dataIndex: 'stationLevel',
    align: 'center',
  },
  {
    title: '建筑形式',
    dataIndex: 'buildingType',
    align: 'center',
  },
  {
    title: '换热站编号',
    dataIndex: 'heatExchangeStationNumber',
    align: 'center',
  },
  {
    title: '热源形式',
    dataIndex: 'heatSourceType',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    align: 'center',
    // 插槽渲染
    scopedSlots: {
      active: 'active',
    },
  },
];
const columns_XQ = [
  {
    title: '所属省',
    dataIndex: 'province',
    align: 'center',
  },
  {
    title: '所属市',
    dataIndex: 'city',
    align: 'center',
  },
  {
    title: '所属区/县',
    dataIndex: 'county',
    align: 'center',
  },
  {
    title: '所属换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    align: 'center',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    align: 'center',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    align: 'center',
  },
  {
    title: '收费方式',
    dataIndex: 'chargeMethod',
    align: 'center',
  },
  {
    title: '建筑年限',
    dataIndex: 'buildingYear',
    align: 'center',
  },
  {
    title: '归属小区',
    dataIndex: 'belongVillage',
    align: 'center',
  },
  {
    title: '小区地址',
    dataIndex: 'villageAddress',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    align: 'center',
    // 插槽渲染
    scopedSlots: {
      active: 'active',
    },
  },
];
const columns_RYH = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'county',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    align: 'center',
  },
  {
    title: '楼栋',
    dataIndex: 'building',
    align: 'center',
  },
  {
    title: '单元',
    dataIndex: 'unit',
    align: 'center',
  },
  {
    title: '房间号',
    dataIndex: 'house',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    align: 'center',
  },
  {
    title: '入户状态',
    dataIndex: 'checkIn',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    align: 'center',
  },
  {
    title: '名单类型',
    dataIndex: 'blacklistType',
    align: 'center',
  },
  {
    title: '使用性质',
    dataIndex: 'houseType',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    align: 'center',
    // 插槽渲染
    scopedSlots: {
      active: 'active',
    },
  },
];
const getTableData = (search: null | number | string | string[] = null) => {
  console.log('getTableData被调用，搜索参数:', search, 'props', props.selectedNodeId);
  switch (props.selectedType) {
    case '小区': {
      return getVillageTableSearch(
        pagination.current,
        pagination.pageSize,
        props.selectedNodeId ? props.selectedNodeId.join(',') : search,
        searchText.value,
      ).then((res: any) => {
        tableData.value = res.data.data;
        pagination.total = res.data.count;
      });
    }
    case '热源': {
      return getHeatSourceTable(
        pagination.current,
        pagination.pageSize,
        props.selectedNodeId ? props.selectedNodeId.join(',') : search,
        searchText.value,
      ).then((res: any) => {
        console.log(res);
        tableData.value = res.data.data;
        pagination.total = res.data.count;
      });
    }
    case '热用户': {
      return getBuildingTableSearch(
        pagination.current,
        pagination.pageSize,
        props.selectedNodeId ? props.selectedNodeId.join(',') : search,
        searchText.value,
      ).then((res: any) => {
        tableData.value = res.data.data;
        pagination.total = res.data.count;
      });
    }
    case '热站': {
      return getHeatStationTableSearch(
        pagination.current,
        pagination.pageSize,
        props.selectedNodeId ? props.selectedNodeId.join(',') : search,
        searchText.value,
      ).then((res: any) => {
        tableData.value = res.data.data;
        pagination.total = res.data.count;
      });
    }
  }
};

// 暴露方法给父组件调用
defineExpose({
  getTableData,
});
// 使用 computed 属性根据 selectedType 动态选择 columns
const dynamicColumns = computed(() => {
  switch (props.selectedType) {
    case '小区': {
      return columns_XQ;
    }
    case '热源': {
      return columns;
    }
    case '热用户': {
      return columns_RYH;
    }
    case '热站': {
      return columns_RZ;
    }
    default: {
      return columns;
    } // 默认返回 '热源' 的 columns
  }
});

// 监听selectedType变化时获取数据
watch(
  () => props.selectedType,
  () => {
    getTableData();
  },
  { immediate: true },
);
const onFile = () => {
  onModel.value = false;
};
// 导出Excel
const onExport = () => {
  // 根据当前选中类型获取对应的表头
  const currentColumns = dynamicColumns.value;

  // 准备表头数据
  const headers = currentColumns.map((col: any) => col.title);

  // 准备表格数据
  const data = tableData.value.map((item: any) => {
    return currentColumns.map((col: any) => {
      // 特殊处理某些字段的显示
      if (col.dataIndex === 'isCompleted') {
        return item[col.dataIndex] === 1 ? '完成' : '未完成';
      }
      // 排除操作列
      if (col.dataIndex === 'active') {
        return '';
      }
      return item[col.dataIndex];
    });
  });

  // 创建工作簿
  const wb = XLSX.utils.book_new();
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet([headers, ...data]);

  // 设置列宽
  const colWidth = headers.map(() => ({ wch: 15 }));
  ws['!cols'] = colWidth;

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, props.selectedType);

  // 生成文件名
  const fileName = `${props.selectedType
    }信息表_${new Date().toLocaleDateString()}.xlsx`;

  // 导出文件
  XLSX.writeFile(wb, fileName);
};

// 导出模板
const onTemplate = () => {
  const templateMap = {
    热源: '/Execl/热源信息表.xls',
    热站: '/Execl/换热站信息表.xls',
    小区: '/Execl/小区信息表.xls',
    热用户: '/Execl/用户信息表.xls',
  };

  const templatePath =
    templateMap[props.selectedType as keyof typeof templateMap];
  if (templatePath) {
    const link = document.createElement('a');
    link.href = templatePath;
    link.download = templatePath.split('/').pop() || '';
    document.body.append(link);
    link.click();
    link.remove();
  }
};
const histToryType = ref('');
const onHistory = () => {
  historyModel.value = true;
  histToryType.value = '导出';
};
const onHistorys = () => {
  historyModel.value = true;
  histToryType.value = '导入';
};
// 详情
const currentRecord = ref<any>(null);

const onDetail = (record: any) => {
  open.value = true;
  console.log(record);
  currentRecord.value = record;
};
const Drawer_Width = computed(() => {
  switch (props.selectedType) {
    case '热站': {
      return '60%';
    }
    case '小区': {
      return '800px';
    }
    case '热用户': {
      return '800px';
    }
    default: {
      return '';
    }
  }
});
const onExportInfo = () => {
  if (props.selectedType == '热源') {
    getRoomBatchOperation_eleven('热源', props.selectedNodeId.join(',')).then(
      (res: any) => {
        if (res.data.data.code == 200) {
          message.success('导出成功');
        } else {
          message.error('导出失败');
        }
      },
    );
  } else if (props.selectedType == '热站') {
    getRoomBatchOperation_eleven('换热站', props.selectedNodeId.join(',')).then(
      (res: any) => {
        if (res.data.data.code == 200) {
          message.success('导出成功');
        } else {
          message.error('导出失败');
        }
      },
    );
  } else if (props.selectedType == '小区') {
    getRoomBatchOperation_eleven('小区', props.selectedNodeId.join(',')).then(
      (res: any) => {
        if (res.data.data.code == 200) {
          message.success('导出成功');
        } else {
          message.error('导出失败');
        }
      },
    );
  } else if (props.selectedType == '热用户') {
    getRoomBatchOperation_eleven('房间', props.selectedNodeId.join(',')).then(
      (res: any) => {
        if (res.data.data.code == 200) {
          message.success('导出成功');
        } else {
          message.error('导出失败');
        }
      },
    );
  }
};
</script>

<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 850px">
        <div class="mb-4 flex items-center justify-between">
          <div class="flex-1"></div>
          <div class="flex items-center gap-2">
            <a-button type="primary" :icon="h(HistoryOutlined)" @click="onExportInfo" v-if="authInfo.exports == 1">
              导出信息
            </a-button>
            <a-button type="primary" :icon="h(HistoryOutlined)" @click="onHistory">导出历史</a-button>
            <!-- <a-button
              type="primary"
              :icon="h(CloudUploadOutlined)"
              @click="onHistory"
            >
              导出历史
            </a-button> -->
            <a-button type="primary" :icon="h(CloudDownloadOutlined)" @click="onModel = true"
              v-if="authInfo.imports == 1">
              导入信息
            </a-button>
            <a-button type="primary" :icon="h(HistoryOutlined)" @click="onHistorys">导入历史</a-button>
            <a-button type="primary" :icon="h(LinkOutlined)" @click="onTemplate">
              导出模板
            </a-button>
            <a-button type="primary" :icon="h(DeleteOutlined)" @click="isDel = true" danger
              v-if="authInfo.deletes == 1">
              批量删除
            </a-button>
            <div class="flex items-center">
              <transition name="slide-fade">
                <a-input v-if="showSearch" v-model:value="searchText" placeholder="请输入搜索内容" class="search-input"
                  @press-enter="handleSearch" @blur="!searchText.trim() && (showSearch = false)" />
              </transition>
              <a-button type="primary" shape="circle" :icon="h(SearchOutlined)"
                @click="showSearch ? handleSearch() : (showSearch = true)" />
            </div>
            <a-button shape="circle" :icon="h(RedoOutlined)" @click="handleRefresh"
              :class="{ 'refresh-spinning': isRefreshing }" />
          </div>
        </div>
        <a-table class="ant-table-striped" size="middle" :columns="dynamicColumns" :data-source="tableData"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)
            " :pagination="pagination" bordered>
          <template #bodyCell="{ column, record }">
            <div v-if="column.dataIndex === 'active'">
              <a-button type="link" @click="onDetail(record)">详情</a-button>
            </div>
            <div v-if="column.dataIndex === 'isCompleted'">
              <a-tag :bordered="false" color="success" v-if="record.isCompleted == 1">
                完成
              </a-tag>
              <a-tag :bordered="false" color="error" v-else>未完成</a-tag>
            </div>
          </template>
        </a-table>
      </a-card>
    </div>
    <!-- <FileUpload
      :open="onModel"
      @on-close="onFile"
      @refresh="getTableData"
      :selected-type="props.selectedType"
    /> -->
    <BatchDelete :open="isDel" @on-close="isDel = false" :selected-type="props.selectedType"
      :selectedNodeId="props.selectedNodeId" :selectedLevel="props.selectedLevel" />
    <HistoryTable :open="historyModel" @on-close="historyModel = false" :selected-type="props.selectedType"
      :histToryType="histToryType" />
    <UploadTemplate :open="onModel" @on-close="onFile" :selected-type="props.selectedType" />
    <DetailRY v-if="props.selectedType === '热源'" :open="open" :data="currentRecord" :selected-type="props.selectedType"
      @handle-close="open = false" @refresh-data="getTableData" :auth="authInfo" />
    <DetailRZ v-if="props.selectedType === '热站'" :open="open" :data="currentRecord" :selected-type="props.selectedType"
      @handle-close="open = false" @refresh-data="getTableData" :auth="authInfo" />
    <DetailXQ v-if="props.selectedType === '小区'" :open="open" :data="currentRecord" :selected-type="props.selectedType"
      @handle-close="open = false" @refresh-data="getTableData" :auth="authInfo" />
    <DetailUser v-if="props.selectedType === '热用户'" :open="open" :data="currentRecord"
      :selected-type="props.selectedType" @handle-close="open = false" @refresh-data="getTableData" :auth="authInfo" />
  </div>
</template>

<style scoped>
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s ease-in;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

.search-input {
  width: 200px;
  margin-right: 8px;
}

.refresh-spinning {
  animation: spin 1s linear;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
